//
//  MTNewsListViewController.m
//  MobTimes
//
//  Created by 江山 王 on 4/30/12.
//  Copyright (c) 2012 Finalist. All rights reserved.
//

#define TIME_AGO_TAG                            (2)
#define COMMENT_COUNT_TAG                       (3)
#define IMAGE_VIEW_TAG                          (4)
#define NEXT_PAGE_LABEL_TAG                     (5)
#define DETAIL_LABEL_TAG                        (6)
#define TITLE_LABEL_TAG                         (7)
#define LAST_CELL_TAG                           (20000)

#define NEXT_PAGE_LABEL_WIDTH                   (100)
#define NEXT_PAGE_LABEL_HEIGHT                  (60)

#define DATA_CELL_HEIGHT                        (80.0f)
#define NEXT_PAGE_CELL_HEIGHT                   (40.0f)

#define IMAGE_VIEW_DEFAULT_WIDTH                (60.0f)
#define IMAGE_VIEW_DEFAULT_HEIGHT               (60.0f)

#import "MTStartupsViewController.h"
#import "MTStartupsModel.h"
#import "MTStartupsPO.h"
#import "MTStartupsCell.h"
#import "MTStartupsContentViewController.h"
#import "MTLabel.h"

@interface MTStartupsViewController ()

@end

@implementation MTStartupsViewController

- (id)initWithURL:(NSString *)url tabbarItemIcon:(NSString *)tabbarItemIcon title:(NSString *)title {
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        _cachedCellImages = [[NSMutableDictionary alloc] init];
        _urlStr = [url retain];
        self.title = title;
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(title, @"Name") image:[UIImage imageNamed:tabbarItemIcon] tag:0];
    }
    return self;
}

- (void)loadView {    
    [super loadView];
}

- (void)viewDidLoad {
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (!_dragRefreshView) {
        _dragRefreshView = [[MTDragRefreshView alloc] init];
        [_dragRefreshView setStatus:MTTableHeaderDragRefreshPullToReload];
        [self.tableView addSubview:_dragRefreshView];
    }
    [super viewDidLoad];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [_cachedCellImages release];
    _cachedCellImages = nil;
    
    [_dragRefreshView release];
    _dragRefreshView = nil;
    
    [_urlStr release];
    _urlStr = nil;
    
    [super dealloc];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //多一个cell用于显示下一页
    if ([(MTStartupsModel *)self.model newsList].count > 0) {
        return [(MTStartupsModel *)self.model newsList].count+1;
    }
    return [(MTStartupsModel *)self.model newsList].count;
}

- (void)loadCellImage:(NSDictionary *)dicData {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
    [dicData retain];
    UITableViewCell *cell = [dicData objectForKey:MT_String("CELL")];
    NSIndexPath *indexPath = [dicData objectForKey:MT_String("INDEX_PATH")];
    
    NSString *_cachedCellImageKey = [NSString stringWithFormat:MT_String("%d-%d"), indexPath.section, indexPath.row];
    MTStartupsPO *_po = [[(MTStartupsModel *)self.model newsList] objectAtIndex:indexPath.row];
    NSString *_imageViewURLString = [_po.imgURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    UIImage *_cachedCellImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_imageViewURLString]]];
    if (_cachedCellImage) {
        [_cachedCellImages setObject:_cachedCellImage forKey:_cachedCellImageKey];
        UIImageView *_imageView = (UIImageView *)[cell.contentView viewWithTag:IMAGE_VIEW_TAG];
        [_imageView performSelectorOnMainThread:@selector(setImage:) withObject:_cachedCellImage waitUntilDone:NO];
        CGSize _cachedCellImageSize = _cachedCellImage.size;
        CGFloat _widthRate = IMAGE_VIEW_DEFAULT_WIDTH/_cachedCellImageSize.width;
        CGFloat _heightRate = IMAGE_VIEW_DEFAULT_HEIGHT/_cachedCellImageSize.height;
        CGFloat _width = IMAGE_VIEW_DEFAULT_WIDTH;
        CGFloat _height = IMAGE_VIEW_DEFAULT_HEIGHT;
        if (_widthRate > _heightRate) {
            _width = _cachedCellImageSize.width * _heightRate;
            _height = _cachedCellImageSize.height * _heightRate;
        } else {
            _width = _cachedCellImageSize.width * _widthRate;
            _height = _cachedCellImageSize.height * _widthRate;
        }
        _imageView.frame = CGRectMake(9, 9, _width, _height);
        MTDebugLog(MT_String("INFO: cell.imageView.frame is %@"), NSStringFromCGRect(cell.imageView.frame));
    }
    [dicData release];
    [pool release];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"news_list_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[MTStartupsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.textLabel.numberOfLines = 1; 
        cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
    }
    
    cell.tag = 0;
    UILabel *_nextPageLabel = (UILabel *)[cell.contentView viewWithTag:NEXT_PAGE_LABEL_TAG];
    if (_nextPageLabel) {
        [_nextPageLabel removeFromSuperview];
    }
    
    //如果不是最后一行
    if (indexPath.row != ([tableView numberOfRowsInSection:indexPath.section]-1)) {        
        MTStartupsPO *_po = [[(MTStartupsModel *)self.model newsList] objectAtIndex:indexPath.row];
        
        //图片
        UIImageView *_imageView = (UIImageView *)[cell.contentView viewWithTag:IMAGE_VIEW_TAG];
        if (!_imageView) {
            _imageView = [[UIImageView alloc] init];
            _imageView.tag = IMAGE_VIEW_TAG;
            [cell.contentView addSubview:_imageView];
        }
        _imageView.frame = CGRectMake(9, 9, IMAGE_VIEW_DEFAULT_WIDTH, IMAGE_VIEW_DEFAULT_HEIGHT);
        _imageView.image = [UIImage imageNamed:MT_String("default_cell_image.png")];
        NSString *_cachedCellImageKey = [NSString stringWithFormat:MT_String("%d-%d"), indexPath.section, indexPath.row];
        UIImage *_cachedCellImage = [_cachedCellImages objectForKey:_cachedCellImageKey];
        if (_cachedCellImage) {
            MTDebugLog(MT_String("CACHED+++++++++++++++++++++++++++++"));
            _imageView.image = _cachedCellImage;
            CGSize _cachedCellImageSize = _cachedCellImage.size;
            CGFloat _widthRate = IMAGE_VIEW_DEFAULT_WIDTH/_cachedCellImageSize.width;
            CGFloat _heightRate = IMAGE_VIEW_DEFAULT_HEIGHT/_cachedCellImageSize.height;
            CGFloat _width = IMAGE_VIEW_DEFAULT_WIDTH;
            CGFloat _height = IMAGE_VIEW_DEFAULT_HEIGHT;
            if (_widthRate > _heightRate) {
                _width = _cachedCellImageSize.width * _heightRate;
                _height = _cachedCellImageSize.height * _heightRate;
            } else {
                _width = _cachedCellImageSize.width * _widthRate;
                _height = _cachedCellImageSize.height * _widthRate;
            }
            _imageView.frame = CGRectMake(9, 9, _width, _height);
        } else {
            MTDebugLog(MT_String("------------------------------------"));
            NSMutableDictionary *_dicData = [[NSMutableDictionary alloc] init];
            [_dicData setObject:indexPath forKey:MT_String("INDEX_PATH")];
            [_dicData setObject:cell forKey:MT_String("CELL")];
            [NSThread detachNewThreadSelector:@selector(loadCellImage:) toTarget:self withObject:_dicData];
            [_dicData release];
            _dicData = nil;
        }
        
        //标题
        MTLabel *_textLabel = (MTLabel *)[cell.contentView viewWithTag:TITLE_LABEL_TAG];
        if (!_textLabel) {
            _textLabel = [[MTLabel alloc] init];
            _textLabel.tag = TITLE_LABEL_TAG;
            [cell.contentView addSubview:_textLabel];
        }
        _textLabel.text = _po.title;
        
        //摘要
        MTLabel *_detailTextLabel = (MTLabel *)[cell.contentView viewWithTag:DETAIL_LABEL_TAG];
        if (!_detailTextLabel) {
            _detailTextLabel = [[MTLabel alloc] init];
            _detailTextLabel.tag = DETAIL_LABEL_TAG;
            [cell.contentView addSubview:_detailTextLabel];
        }
        _detailTextLabel.text = _po.abstract;
        
        //作者
        if (_po.author) {
            UILabel *_authorLabel = (UILabel *)[cell.contentView viewWithTag:AUTHOR_LABEL_TAG];
            if (!_authorLabel) {
                _authorLabel = [[UILabel alloc] init];
                [_authorLabel setTag:AUTHOR_LABEL_TAG];
                [cell.contentView addSubview:_authorLabel];
            }
            [_authorLabel setText:[NSString stringWithFormat:MT_String("%@ 发布于 %@"), _po.author, _po.timeAgo]];
        }
    } else {
        cell.textLabel.text = nil;
        cell.detailTextLabel.text = nil;
        cell.imageView.image = nil;
        cell.tag = LAST_CELL_TAG;
        
        //标题
        MTLabel *_textLabel = (MTLabel *)[cell.contentView viewWithTag:TITLE_LABEL_TAG];
        if (_textLabel) {
            _textLabel.text = nil;
        }
        
        //摘要
        MTLabel *_detailTextLabel = (MTLabel *)[cell.contentView viewWithTag:DETAIL_LABEL_TAG];
        if (_detailTextLabel) {
            _detailTextLabel.text = nil;
        }
        
        //作者
        UILabel *_authorLabel = (UILabel *)[cell.contentView viewWithTag:AUTHOR_LABEL_TAG];
        if (_authorLabel) {
            _authorLabel.text = nil;
        }
        UIImageView *_imageView = (UIImageView *)[cell.contentView viewWithTag:IMAGE_VIEW_TAG];
        if (_imageView) {
            _imageView.frame = CGRectZero;
            _imageView.image = nil;
        }
        
        UILabel *_nextPageLabel = (UILabel *)[cell.contentView viewWithTag:NEXT_PAGE_LABEL_TAG];
        if (!_nextPageLabel) {
            _nextPageLabel = [[UILabel alloc] initWithFrame:CGRectMake((cell.frame.size.width-NEXT_PAGE_LABEL_WIDTH)/2.0f, 
                                                                       (NEXT_PAGE_CELL_HEIGHT-NEXT_PAGE_LABEL_HEIGHT)/2.0f, 
                                                                       NEXT_PAGE_LABEL_WIDTH, 
                                                                       NEXT_PAGE_LABEL_HEIGHT)];
            _nextPageLabel.textAlignment = UITextAlignmentCenter;
            _nextPageLabel.backgroundColor = [UIColor clearColor];
            _nextPageLabel.font = [UIFont systemFontOfSize:20];
            _nextPageLabel.text = MT_String("显示下一页");
            _nextPageLabel.tag = NEXT_PAGE_LABEL_TAG;
            [cell.contentView addSubview:_nextPageLabel];
        }
    }
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *_selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    if (_selectedCell && _selectedCell.tag == LAST_CELL_TAG) {
        [self.model loadData];
    } else {
        MTStartupsPO *_po = [[(MTStartupsModel *)self.model newsList] objectAtIndex:indexPath.row];
        MTStartupsContentViewController *_newsContentViewController = [[MTStartupsContentViewController alloc] initWithNewsContentURLStr:_po.detailURLString];
        [self.navigationController pushViewController:_newsContentViewController animated:YES];
        [_newsContentViewController release];
        _newsContentViewController = nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row != ([(MTStartupsModel *)self.model newsList].count)) {
        return DATA_CELL_HEIGHT;
    } else {
        return NEXT_PAGE_CELL_HEIGHT;
    }
}

#pragma mark - UIScrollViewDelegate

// any offset changes
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	if (self.model.isLoading) {
		if (scrollView.contentOffset.y >= 0) {
			self.tableView.contentInset = UIEdgeInsetsZero;
		} else if (scrollView.contentOffset.y < 0) {
            [_dragRefreshView setStatus:MTTableHeaderDragRefreshLoading];
			self.tableView.contentInset = UIEdgeInsetsMake(MTDragRefreshViewHeight, 0, 0, 0);
		}
	} else {
        CGPoint _liveContentOffset = [scrollView contentOffset];
        if (_liveContentOffset.y < -MTDragRefreshViewHeight) {
            [_dragRefreshView setStatus:MTTableHeaderDragRefreshReleaseToReload];
        } else {
            [_dragRefreshView setStatus:MTTableHeaderDragRefreshPullToReload];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate {
	// If dragging ends and we are far enough to be fully showing the header view trigger a
	// load as long as we arent loading already
	if (scrollView.contentOffset.y <= -MTDragRefreshViewHeight && !self.model.isLoading) {
		[self.model reloadData];
	}
//    shouldUpdateRefreshTime = YES;
}

#pragma mark - Public methods implementation

- (MTModel *)createModel {
    return [[[MTStartupsModel alloc] initWithController:self andURLStr:_urlStr] autorelease];
}

- (void)setDraggingRefreshStatus:(MTTableHeaderDragRefreshStatus)status {
    if (_dragRefreshView) {
        [_dragRefreshView setStatus:status];
    }
}

@end